﻿   using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_ShippingListBusiness : BaseBusiness<PB_ShippingList>, IPB_ShippingListBusiness, ITransientDependency
    {
        readonly IOperator _operator;


        public PB_ShippingListBusiness(IDbAccessor db, IOperator @operator, IPB_MaterialBusiness pBMaterialBusiness, IPB_DesignListBusiness pB_DesignListBusiness)
            : base(db)
        {
            _operator = @operator;
            _pBMaterialBusiness = pBMaterialBusiness;
            _pB_DesignListBusiness = pB_DesignListBusiness;

        }
        IPB_MaterialBusiness _pBMaterialBusiness { get; }
        IPB_DesignListBusiness _pB_DesignListBusiness { get; }

        #region 外部接口

        public async Task<PageResult<PB_ShippingList>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_ShippingList>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_ShippingList, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_DeliverGoodDetailDTO> GetDataListByBuildNoAsync(string id,string DesignId)
        {
            // var main = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == id).ToList();
            //获取清单主表
            PB_DeliverGoodDetailDTO dto = new PB_DeliverGoodDetailDTO();
            dto.Main= Db.GetIQueryable<PB_DesignList>().FirstOrDefault(s => s.Id == DesignId);
            //获取子表物料明细
            StringBuilder sql = new StringBuilder();
            sql.Append("select ");
            sql.Append(" a.Id,a.Id SubId,");
            sql.Append("a.MaterialId,");
            sql.Append("b.`Name` MaterialName,b.`Code` MaterialCode,");
            sql.Append("u.`Name` storageName,");
            sql.Append("ifnull(b.Weight,0) Weight,");
            sql.Append("b.StorageId,");
            sql.Append("a.Nums,");
            sql.Append("a.RealNums,");
            sql.Append("ifnull(c.EstimatedQuantity,0) EstimatedQuantity,");
            sql.Append("ifnull(a.ShipmentNums,0) ShipmentNums ");
            sql.Append("from PB_DesignDetail a ");
            sql.Append("left join PB_Material b on a.MaterialId=b.Id ");
            sql.Append("left join Base_UnitItems u on b.storageId=u.Id ");
            sql.Append("left join PB_ShippingList c on a.Id=c.SubId ");
            sql.Append("where a.ParentId='");
            sql.Append(DesignId);
            sql.Append("'");
            sql.Append(" AND c.ParentId='");
            sql.Append(id);
            sql.Append("'");
            dto.Sub = await Db.GetListBySqlAsync<PB_PB_DesignMaterials>(sql.ToString());
            if (dto.Sub.Count > 0)
            {
                return dto;

            }
            else {
                StringBuilder sqlout = new StringBuilder();
                sqlout.Append("select ");
                sqlout.Append(" a.Id,a.Id SubId,");
                sqlout.Append("a.MaterialId,");
                sqlout.Append("b.`Name` MaterialName,b.`Code` MaterialCode,");
                sql.Append("u.`Name` storageName,");
                sqlout.Append("ifnull(b.Weight,0) Weight,");
                sqlout.Append("b.StorageId,");
                sqlout.Append("a.Nums,");
                sqlout.Append("a.RealNums,");
                sqlout.Append("ifnull(c.EstimatedQuantity,0) EstimatedQuantity,");
                sqlout.Append("ifnull(a.ShipmentNums,0) ShipmentNums ");
                sqlout.Append("from PB_DesignDetail a ");
                sqlout.Append("left join PB_Material b on a.MaterialId=b.Id ");
                sql.Append("left join Base_UnitItems u on a.storageId=u.Id ");
                sqlout.Append("left join PB_ShippingList c on a.Id=c.SubId ");
                sqlout.Append("where a.ParentId='");
                sqlout.Append(DesignId);
                sqlout.Append("'");
                dto.Sub = await Db.GetListBySqlAsync<PB_PB_DesignMaterials>(sqlout.ToString());
                return dto;
            }
        }

        public async Task<PB_ShippingList> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_ShippingList data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_ShippingList data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }
        #endregion

        public async Task AddMaterialData(SaveMaterialData data)
        {
            List<PB_ShippingList> ListDesignDetail = new List<PB_ShippingList>();
            #region 发货通知单
            PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
            string dataId = IdHelper.GetId();
            pB_WarehousingNotice.Id = dataId;
            pB_WarehousingNotice.QrCode = "20," + dataId;
            pB_WarehousingNotice.DeptId = _operator.Property.DepartmentId;
            pB_WarehousingNotice.CreatorName = _operator.Property.UserName;
            pB_WarehousingNotice.CreateTime = DateTime.Now;
            pB_WarehousingNotice.CreatorId = _operator.UserId;
            pB_WarehousingNotice.Deleted = false;
            pB_WarehousingNotice.Type = 3;
            await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);
            #endregion
            #region 组装数据
            for (int i = 0; i < data.subMData?.Count; i++)
            {
                PB_ShippingList pB_DesignDetail = new PB_ShippingList();
                pB_DesignDetail.Id = IdHelper.GetId();//详情id
                pB_DesignDetail.ParentId = data.PId;//设计清单主表id
                pB_DesignDetail.SubId = data.subMData[i].SubId;
                pB_DesignDetail.MaterialId = data.subMData[i].MaterialId;//物料id
                pB_DesignDetail.Nums = data.subMData[i].Nums;//设计数量
                pB_DesignDetail.EstimatedQuantity = data.subMData[i].RealNums;//实发数量
                pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                pB_DesignDetail.Deleted = false;//伪删除
                pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                pB_DesignDetail.OddNumber = dataId;//理论重量

                ListDesignDetail.Add(pB_DesignDetail);
            }
            await Db.InsertAsync(ListDesignDetail);
            #endregion
        }

        public async Task UpdateMaterialData(SaveMaterialData data)
        {
            //字表信息
            List<PB_ShippingList> ListDesignDetail = new List<PB_ShippingList>();
            //先删除原有的关联数据
            var where = LinqHelper.True<PB_ShippingList>();
            if (!data.PId.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_ShippingList, bool>(
                        ParsingConfig.Default, false, $@"ParentId.Equals(@0)", data.PId);
                where = where.And(newWhere);
            }
            var DbInfo = Db.GetIQueryable<PB_ShippingList>();

            var intrunt = await ExecuteSqlAsync("DELETE FROM PB_ShippingList WHERE ParentId in ('" + data.PId + "')");
            #region 发货通知单
            PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
            string dataId = IdHelper.GetId();
            pB_WarehousingNotice.Id = dataId;
            pB_WarehousingNotice.QrCode = "20," + dataId;
            pB_WarehousingNotice.DeptId = _operator.Property.DepartmentId;
            pB_WarehousingNotice.CreatorName = _operator.Property.UserName;
            pB_WarehousingNotice.CreateTime = DateTime.Now;
            pB_WarehousingNotice.CreatorId = _operator.UserId;
            pB_WarehousingNotice.Deleted = false;
            pB_WarehousingNotice.Type = 3;
            await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);
            #endregion
            #region 组装数据
            for (int i = 0; i < data.subMData.Count; i++)
            {
                    PB_ShippingList pB_DesignDetail = new PB_ShippingList();
                    pB_DesignDetail.Id = IdHelper.GetId();//详情id
                    pB_DesignDetail.ParentId = data.PId;//设计清单主表id
                    pB_DesignDetail.SubId = data.subMData[i].SubId;
                    pB_DesignDetail.MaterialId = data.subMData[i].MaterialId;//物料id
                    pB_DesignDetail.Nums = data.subMData[i].Nums;//设计数量
                    pB_DesignDetail.EstimatedQuantity = data.subMData[i].EstimatedQuantity;//实发数量
                    pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                    pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                    pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                    pB_DesignDetail.Deleted = false;//伪删除
                    pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                    pB_DesignDetail.OddNumber = dataId;//理论重量
                    ListDesignDetail.Add(pB_DesignDetail);
            }
            #endregion

            await Db.InsertAsync(ListDesignDetail);
        }

        public async Task<List<DataTypeInfo>> GetDataLisJson(string id)
        {
            List<DataTypeInfo> dataTypeInfos = new List<DataTypeInfo>();
            var q = _pB_DesignListBusiness.GetTypeAsyncs(id).Result;
            List<PB_MaterialDTO> list = await _pBMaterialBusiness.QueryDataQueryDeliverAsync(string.Join(",", q.Select(n => n.MaterialID).ToArray()), id);
            DataTypeInfo dataTypeInfo = new DataTypeInfo();
            dataTypeInfo.Data = q.FirstOrDefault();
            dataTypeInfo.Sub = list?.ToList();
            dataTypeInfos.Add(dataTypeInfo);
            return  dataTypeInfos;
        }

        public Task<List<DataTypeInfo>> GetShippingOrder(string id)
        {
            //List<DataTypeInfo> dataTypeInfos = new List<DataTypeInfo>();
            //var q = _pB_DesignListBusiness.GetTypeAsyncs(id).Result;
            //List<PB_MaterialDTO> list = await _pBMaterialBusiness.QueryDataQueryDeliverAsync(string.Join(",", q.Select(n => n.MaterialID).ToArray()), id);
            //DataTypeInfo dataTypeInfo = new DataTypeInfo();
            //dataTypeInfo.Data = q.FirstOrDefault();
            //dataTypeInfo.Sub = list?.ToList();
            //dataTypeInfos.Add(dataTypeInfo);
            //return dataTypeInfos;
            return null;
        }


        #region 私有成员

        #endregion
    }
}